<?php
/**
 * Created by allen.qiang <allen.qiang@fistforward.com>
 * Date: 15-1-12
 * FUN-AC-0028
 * 下午茶套餐操作类
 */

class dunch{
    /*
     * 查询下午茶套餐配置信息
     */
    public function searchPackage(&$arg_array){
        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();


        //套餐ID
        if (isset($arg_array['package_id']) && !empty($arg_array['package_id'])) {
            $sql .= ' AND package_id = ?';
            $params_type .= 's';
            $params_array[] =  $arg_array['package_id'] ;
        }
        //套餐名称
        if (isset($arg_array['package_name']) && !empty($arg_array['package_name'])) {
            $sql .= ' AND package_name LIKE ?';
            $params_type .= 's';
            $params_array[] = "%" . $arg_array['package_name'] . "%";
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM dunch_package ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
            } else {

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM dunch_package ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach ($temp_item_array as &$item) {
                $item_array[] = array(
                    'package_id' => $item->package_id,
                    'package_name' => $item->package_name,
                    'package_price' => $item->package_price,
                    'package_remark' => $item->package_remark,
                    'package_remark_2' => $item->package_remark_2,
                    'package_image' => $item->package_image

                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }
    }




    /*
     * 查询下午茶列表信息
     */
    public function searchDunch(&$arg_array){
        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();


        //销售时间
        if (isset($arg_array['send_date']) && !empty($arg_array['send_date'])) {
            $sql .= ' AND sale_date = ?';
            $params_type .= 's';
            $params_array[] =  $arg_array['send_date'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {
            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM dunch_sale join dunch_package as b on dunch_sale.package_id=b.package_id ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;


                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
            } else {

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM dunch_sale join dunch_package as b on dunch_sale.package_id=b.package_id ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
            foreach ($temp_item_array as &$item) {
                $item_array[] = array(
                    'sale_id'=>$item->sale_id,
                    'sale_date' => $item->sale_date,
                    'package_name' => $item->package_name,
                    'package_id' => $item->package_id,
                    'package_image' => $item->package_image,
                    'package_price' => $item->package_price,
                    'package_num' => $item->package_num,
                    'right_num' => $item->right_num,
                    'use_num' => $item->use_num,
                    'package_image_2' => $item->package_image_2,
                    'package_image_3' => $item->package_image_3,
                    'package_remark'=> $item->package_remark,
                    'package_remark_2'=> $item->package_remark_2,

                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }
    }
    /*
     * 咖啡验收列表查询·
     */

    public function searchCoffee(&$arg_array){


        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();


        //套餐名称
        if (isset($arg_array['accept_date']) && !empty($arg_array['accept_date'])) {
            $sql .= ' AND accept_date = ?';
            $params_type .= 's';
            $params_array[] =  $arg_array['accept_date'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM dunch_accept ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;


                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
            } else {

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM dunch_accept' . $sql;

            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
            foreach ($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'=>$item->creator,
                    'accept_id'=>$item->accept_id,
                    'brandID' => $item->brandID,
                    'createTime' => $item->createTime,
                    'remark' => $item->remark,
                    'distribution_id' => $item->distribution_id

                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }



    /**
     *add by junhui.li
     *计算每个订单的价格舍余取整数，26/3 = 8，8，10
     *create_time 2015-06-09 13:13:30
     * param $totalMoney 订单的总价格
     * param $totalNum 总套餐数
     */
    public function calculationData($totalMoney,$totalNum){
        try{
            $array=array();
            if($totalNum==1){
                $array[0]=$totalMoney;
            }else{
                $avgTotal=intval($totalMoney/$totalNum);
                for($i=0;$i<=$totalNum-1;$i++){
                    if($i<$totalNum-1){
                        $array[$i]=$avgTotal;
                    }else if($i=$totalNum-1){
                        $array[$i]=$totalMoney-$avgTotal*($i);
                    }else{
                        break;
                    }
                }
            }
        }catch (Exception $ex){

            error_log($ex->getMessage());
        }
        return $array;

    }

    /**
     * add by junhui.li
     * 区分咖啡和蛋糕
     * create_time 2015-06-09 16:13:30
     * param $sys_item_data 查询sku
     * param $goods_array 提交的套餐信息
     * param $avgPrice
     */

    public function avgPriceArray($sys_item_data,$goods_array,$avgPrice){

        $avgPriceKey=0;
        foreach($goods_array as $key=>$value){
            if(strstr($sys_item_data[0]->itemName,$value['sku'])){
                $goods_array[$key]['coffeePrice']=0;
            }
            if(strstr($sys_item_data[1]->itemName,$value['sku'])){
                $goods_array[$key]['coffeePrice']=$avgPrice[$avgPriceKey];
                $avgPriceKey++;
            }
        }
        return $goods_array;
    }



    /*
     * 创建订单
     */
    public function create_bill( $bill ) {//,$config_array
        global $G_SHOP;

        $price_money=0;
        $info=$G_SHOP->sessionCache_get('info_text');
        foreach($info as $goodsCode){
            foreach($goodsCode as $key=>$goodsCode1){
                foreach($goodsCode1 as $goodsCode2){

                    for($num = 1; $num<=$goodsCode2['num'];$num++)
                    {
                        $goods_array[] = array(
                            'sku' => $goodsCode2['code'],
                            'num' => 1
                        );

                    }
                }
                $packageSql="select package_price from  dunch_package  where package_id=?";

                $packageQuest=$G_SHOP->DBCA->stmt_query($packageSql,'s',$key);

                $price_money+=$packageQuest[0]->package_price*$goodsCode2['num'];


            }

        }


//        error_log(print_r($goods_array,1));
        //$bill['deliver_mobile']
        $bill['deliver_provinceid'] = 10; //省
        $bill['deliver_cityid'] = 110;  //市
        //$bill['country']

        //$bill['deliver_name']
        //$bill['deliver_address']
        //$bill['deliver_mobile']

        $bill['invoice_type'] = 1; //发票类型： 1、商业零售发票
        //$bill['invoice_title_type'] //1：个人 2：单位
        //$bill['invoice_title'] //发票抬头
        $bill['invoice_content'] = null;//发票内容
        $bill['invoice_amount'] = 1; //发票金额
        $bill['invoice_number'] = null;//发票号
        $bill['is_the_invoice']=0;  //是否开票 1、是 0、否
        $bill['is_urgent'] = 3;


        //$bill['payTypeID']
        //$bill['payment_method_id']

        //$bill['send_date']
        //$bill['send_start_time']
        //$bill['send_end_time']

        $bill['remark'] = '';
        $bill['billChannel'] = 1;
        $bill['billType'] = 1;

        //$bill['billPromotion']
        $bill['external_bill_no'] = null;



        quanli_require('module/base/customer/quanliCust.class.php');
        quanli_require('module/base/customer/custDeliver.class.php');
        quanli_require('module/base/customer/custInvoice.class.php');
        quanli_require('module/base/system/sysRegion.class.php');
        quanli_require('module/base/system/sysDistribution.class.php');
        quanli_require('module/base/system/sysDistributionTechnician.class.php');
        quanli_require('module/base/system/sysPayment.class.php');
        quanli_require('module/base/bill/billCheckout.class.php');
        quanli_require('module/base/bill/billSearch.class.php');
        quanli_require('module/base/system/sysSend.class.php');
        quanli_require('module/base/goods/quanliGoods.class.php');
        quanli_require('module/base/goods/goodsFittings.class.php');
        quanli_require('module/base/promotion/quanliCoupon.class.php');
        quanli_require('module/base/promotion/quanliCard.class.php');


        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        $quanliCust = new quanliCust();
        $custDeliver = new custDeliver();
        $custInvoice = new custInvoice();
        $sysDistribution = new sysDistribution();
        $sysPayment = new sysPayment();
        $billCheckout = new billCheckout();
        $sysSend = new sysSend();
        $sysRegion = new sysRegion( $G_SHOP->DBCA );




        /**
         * ==============================
         * 查询会员信息（如不存在则新建）
         * ==============================
         */


//        if(!isset($bill['deliver_mobile']) || empty($bill['deliver_mobile']))
//        {
//            return array('code'=>404,'message'=>'请输入');
//        }

        $args_array = array(
            'custID' => $bill['custID']
        );
        $customer_array = $quanliCust->searchCustomerDetail( $args_array );
        if (!$customer_array) {
            return array('code'=>404,'message'=>'会员信息不存在,请先注册');
            //实例会员类
//            $quanliCust = new quanliCust();
//            //前台注册会员信息
//            $reg_args_array = array(
//                'custID' => $args_array['custID'],
//                'pwd' => '888888',
//                'pwd2' => '888888',
//                'custSource' => 4,
//                'custType' => 2
//            );
//            $reg_result_array = $quanliCust->register( $reg_args_array );
//            if ($reg_result_array['code'] == 200) {
//                $customer_array = $quanliCust->searchCustomerDetail( $args_array );
//            }
//            else{
//                return $reg_result_array;
//            }
        }

        //error_log(print_r($customer_array,1));

//        $tmp_bill_master = new entity('bill_master');
//        $tmp_bill_master->custID = $bill['custID'];
//        $tmp_bill_master->billPromotion = $bill['billPromotion'];
//        $G_SHOP->DBCA->fetch($tmp_bill_master);
//
//        if(!$tmp_bill_master ||  $tmp_bill_master->bill_no)
//        {
//            return array('code'=>'404','message'=>'您已订购过,不能再次订购!');
//        }



//        $comp_result = $this->isCompetence($args_array);
//        if($comp_result['code'] != 200)
//        {
//            return $comp_result;
//        }



        //>>>>>>>>>>>>>>>>>//单量控制>>>>>>>>>>>>>>>>>>>
//        $send_date_array = explode(',',$config_array['send_date_array']);
//        $send_date_array_sw = explode(',',$config_array['send_date_array_sw']);
//        $send_date_bill_limit_array = explode(',',$config_array['send_date_bill_limit_array']);
//
//        $send_date_array_sql = array();
//        foreach($send_date_array as $date_item)
//        {
//            $send_date_array_sql[] = "'$date_item'";
//        }
//
//        $sql_string = "SELECT bill_master.send_date,COUNT(1) AS bill_sum FROM bill_master
//                    INNER JOIN bill_goods ON bill_master.bill_no = bill_goods.bill_no
//                    WHERE bill_master.billPromotion = ".$config_array['billPromotion']."
//                    AND bill_goods.product_code = '".$config_array['sku']."'
//                    AND bill_master.send_date IN (". implode(',',$send_date_array_sql) .")
//                    GROUP BY bill_master.send_date
//                    ";
//
//        $bill_array_sum = array();
//
//        $tmp_bill_array_sum = $G_SHOP->DBCA->stmt_query($sql_string);
//        if($tmp_bill_array_sum)
//        {
//            foreach($tmp_bill_array_sum as $sum)
//            {
//                $bill_array_sum[$sum->send_date] = $sum->bill_sum;
//            }
//
//        }
//
//
//        if( in_array($bill['send_date'],$send_date_array)) //配送日期开关
//        {
//            $index = array_search($bill['send_date'],$send_date_array);
//            if($send_date_array_sw[$index]==0)
//            {
//                return array('code'=>'404','message'=>'该配送日期已达上限，请重新选择');
//            }
//
//            if($send_date_bill_limit_array[$index]>0)
//            {
//                if( isset($bill_array_sum[$bill['send_date']]) && $bill_array_sum[$bill['send_date']] >= $send_date_bill_limit_array[$index])
//                {
//                    return array('code'=>'404','message'=>'该配送日期已达上限，请重新选择');
//                }
//            }
//            else
//            {
//                return array('code'=>'404','message'=>'该配送日期已达上限，请重新选择');
//            }
//        }
//        else
//        {
//            return array('code'=>'404','message'=>'配送日期不正确，请重新选择');
//        }

        /**
         * =====================
         * 省市区查询
         * =====================
         */
        $args_array = array(
            'id' => $bill['deliver_provinceid'],
            'region_level' => 1
        );
        $province_array = $sysRegion->getAreaManageList( $args_array );
        $args_array = array(
            'id' => $bill['deliver_cityid'],
            'region_level' => 2
        );
        $city_array = $sysRegion->getAreaManageList( $args_array );
        $args_array = array(
            'id' => $bill['country'],
            'region_level' => 3
        );
        $county_array = $sysRegion->getAreaManageList( $args_array );


        /**
         * ================
         * 收货地址
         * ================
         */
        $args_array = array(
            'pcustID' => $customer_array['pcustID'],
            'creator' => $bill['custID'],
            'custName' => $bill['deliver_name'],
            'provinceid' => $province_array[0]['id'],
            'cityid' => $city_array[0]['id'],
            'countyid' => $county_array[0]['id'],
            'address' => $bill['deliver_address'],
            'mobile' => $bill['deliver_mobile'],
            'phone' => ''
        );



        $deliver_array_s = $custDeliver->searchCustDeliver( $args_array );


        if($deliver_array_s)
        {
            $deliver_array = $deliver_array_s[0];
        }
        else
        {
            $result_deliver = $custDeliver->editCustDeliver( $args_array );
            $dunch_address=new entity("dunch_address");
            $dunch_address->pcustID=$result_deliver['data']['pcustID'];
            $dunch_address->deliverID=$result_deliver['data']['deliverID'];
            $G_SHOP->DBCA->save($dunch_address);
            if ($result_deliver['code'] != 200) {
                return $result_deliver;
            }
            else
            {
                $deliver_array = $result_deliver['data'];
            }
        }







        /**
         * ================
         * 发票
         * ================
         */
//        if ($bill['invoice_title_type']) {
//            $args_array = array(
//                'creator' =>$bill['custID'],
//                'pcustID' => $customer_array['pcustID'],
//                'invoice_type' => $bill['invoice_type'],
//                'invoice_title_type' => $bill['invoice_title_type'],
//                'invoice_title' => $bill['invoice_title'],
//            );
//            $result_array = $custInvoice->editCustInvoice( $args_array );
//            if ($result_array['code'] == 200) {
//                $invoice_array = $result_array['data'];
//            }
//        }




        /**
         * ================
         * 查询配送站
         * ================
         */
        $areaID = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 1,463);//测试环境458 正式463


        if($areaID['areaID'] == 0)
        {
            //return array('code'=>404,'message'=>print_r($areaID,1));
            return array('code'=>404,'message'=>'抱歉该地址不属于配送区域!');
        }


        //查询地图区域和配送站的映射关系
        $args_array = array(
            'areaID' => $areaID['areaID']
        );
        $distribution_map_area = $sysDistribution->searchDistributionMapArea( $args_array );
        if($distribution_map_area) {
            $distribution_id = $distribution_map_area[0]['distribution_id'];
        }

        if (isset($distribution_id)) {
            //查询配送站
            $args_array = array(
                'distribution_id' => $distribution_id,
                'useFlg' => 1
            );
            $distribution_array = $sysDistribution->search( $args_array );
        }


        /**
         * ================
         * 查询配送方式
         * ================
         */
        $result_array = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 2,463);//测试环境458 正式463
        $areaID = $result_array['areaID'];
        if ($areaID == 0) {
            $areaID = $result_array['default_areaID'];
        }
//
        //查询地图区域下的所有配送区域
        $args_array = array(
            'areaID' => $areaID
        );
        $send_area_array = $sysSend->searchSendArea( $args_array );
        if (!$send_area_array) {
            return $send_area_array;
        }
//
        //根据配送区域查询配送方式
        $args_array = array(
            'sendTypeID' => $send_area_array[0]['sendTypeID']
        );
        $sendType_array = $sysSend->searchSendType( $args_array );

        if($send_area_array[0]['freight'] > 0)
        {
            return array('code'=>404,'message'=>'抱歉,该地址不属于配送区域!');
        }





        $bill_no = generate_seqno('seqno_bill');
        $bill_code = $city_array[0]['alias'] . get_bill_code( 'seqno_bill_code' . $city_array[0]['alias'] );

        /**
         * ================
         * 查询支付方式
         * ================
         */
        $pay_type_array = $sysPayment->searchPayTypeDetail( $bill['payTypeID'] );

        if (!$pay_type_array) {
            return $pay_type_array;
        }

        if ($pay_type_array['type'] == 1 ) {
            if (!isset($bill['payment_method_id']) || !quanli_is_int($bill['payment_method_id'])) {
                return array('code'=>404,'message'=>'支付方式不存在');
            }
            $args_array = array(
                'id' => $bill['payment_method_id']
            );


            $payment_array = $sysPayment->searchPaymentMethod( $args_array );

            if (!$payment_array) {
                returnJsonData('支付方式不存在', 404);
            }
        }

//
        $bill_totalMoney = 0;//订单总金额,根据商品的标准售价计算出的，不含运费
        $bill_totalPaid = 0;//订单商品实际成交金额,不含运费，不含附加费
        $bill_accessories_money = 0; //订单配件金额
        $bill_subtract_money = 0; //订单立减金额
        $bill_coupon_money = 0; //订单优惠券订单金额
        $bill_card_money = 0; //代金卡抵扣金额
        $bill_paying_agent_money = 0; //代付订单总金额
        $bill_points_money = 0; //订单总积分价格??????
        $bill_balance_money = 0; //余额抵扣金额
        $bill_online_money = 0; //在线支付已付金额
        $deliver_fee = $send_area_array[0]['freight']; //运费
        $deliver_feePaid = $deliver_fee; //实收运费



//        if (isset($bill_data['bill_master']['deliver_feePaid']) && $bill_data['bill_master']['deliver_feePaid'] != '') {
//            $deliver_feePaid = $bill_data['bill_master']['deliver_feePaid']; //实收运费
//        } else {
//            $deliver_feePaid = $send_area_array[0]['freight']; //实收运费
//        }
        $bill_totalAmount = 0;
//
//
        //临时数组
        $temp_array = array(
            'pay_id' => array(),
            'pay_name' => array(),
            'goods' => array(),
            'coupon_code' => array(),
            'card_code' => array(),
            'paying_agent_str' => array()
        );


        /**
         * ===================
         * 订单商品
         * ===================
         */
        $bill_goods_array = array();

        $bill_goods_fittings_array = array();

        $tableware_amount = 0;

        $candle_amount = 0;

        //区分饮品还是蛋糕 start
        $sys_item_sql = 'SELECT * FROM sys_item WHERE itemCategoryID=36';
        $sys_item_data = &$G_SHOP->DBCA->stmt_query($sys_item_sql);
        $avgPrice=$this->calculationData($price_money,count($goods_array)/2);
        $goods_array=$this->avgPriceArray($sys_item_data,$goods_array,$avgPrice);
        //区分饮品还是蛋糕 end
        foreach($goods_array as &$goods) {

            $args_array = array(
                'product_code' => $goods['sku'],
            );
            $goods_info = $quanliGoods->searchGoodsSaleDetail( $args_array );
            if (!$goods_info) {
                return  array(
                    'code' => 404,
                    'message' => '没有商品' . $goods['sku']
                );
            }

            $bill_goods_obj = new entity('bill_goods');
            $bill_goods_obj->creator = $bill['custID'];
            $bill_goods_obj->bill_no = $bill_no;
            $bill_goods_obj->bill_goods_no = generate_seqno('seqno_bill_goods');
            $bill_goods_obj->goods_goodsID = $goods_info['goodsID'];
            $bill_goods_obj->goods_postID = $goods_info['postID'];
            $bill_goods_obj->product_code = $goods_info['product_code'];
            $bill_goods_obj->goods_name = $goods_info['goodsName'];
            $bill_goods_obj->goods_spec = $goods_info['spec'];
            $bill_goods_obj->goods_amount = $goods['num'];
            $bill_goods_obj->goods_marketPrice = $goods_info['marketPrice'];
            $bill_goods_obj->goods_storePrice = $goods_info['salePrice'];
            //add by junhui.li 20150609 订单金额优化 start
            //$bill_goods_obj->goods_purchasePrice = $goods_info['salePrice'];
            $bill_goods_obj->goods_purchasePrice = $goods['coffeePrice'];
            //add by junhui.li 20150609 订单金额优化 end
            $bill_goods_obj->goods_pointsPrice = 0;
            $bill_goods_obj->goods_points = 0;
            $bill_goods_obj->goods_weight = 0;
            $bill_goods_obj->goods_from = 1;
            $bill_goods_obj->goods_groupID = 0;
            $bill_goods_obj->goods_remark = isset($goods['goods_remark']) ? $goods['goods_remark'] : null;
            $bill_goods_obj->birthday_card = isset($goods['birthday_card']) ? $goods['birthday_card'] : null;
            $bill_goods_obj->segmentation = isset($goods['segmentation']) ? $goods['segmentation'] : 0;
            $bill_goods_array[] = $bill_goods_obj;
            $bill_totalAmount++;

            $bill_totalMoney += $bill_goods_obj->goods_storePrice;
            $bill_totalPaid += $bill_goods_obj->goods_purchasePrice;
            $temp_array['goods'][] =  $goods_info['goodsName'];




        }

        //订单金额
        $bill_money = $price_money;

        //订单应收金额
        $bill_receivable_money = $price_money;


        $bill_pay_array = array();


        //保存订单支付信息
        $pay_status = 0;
        if ($bill_receivable_money >= 0) {

            if ($bill_receivable_money == 0) {
                $pay_status = 2;
            }

            $bill_pay_obj = new entity('bill_pay');
            $bill_pay_obj->creator = $bill['custID'];
            $bill_pay_obj->bill_no = $bill_no;
            $bill_pay_obj->payTypeID = $pay_type_array['payTypeID'];
            $bill_pay_obj->payTypeName = $pay_type_array['payTypeName'];
            $bill_pay_obj->type = $pay_type_array['type'];
            $bill_pay_obj->pay_amount = $bill_receivable_money;
            if ($pay_type_array['type'] == 1) {
                $bill_pay_obj->deduct_amount = 0;
                $bill_pay_obj->payment_method_id = $payment_array[0]['id'];

                $bill_pay_obj->payment_method_name = $payment_array[0]['name'];
                $bill_pay_obj->payment_method_type = $payment_array[0]['type'];


            } else {
                $bill_pay_obj->deduct_amount = 0;
            }

            $bill_pay_array[] = $bill_pay_obj;

            $temp_array['pay_id'][] = $pay_type_array['payTypeID'];
            $temp_array['pay_name'][] = $pay_type_array['payTypeName'];

        }

        $bill_master = new entity('bill_master');
        $bill_master->creator = $bill['custID'];
        if (!empty($bill['createTime'])) {
            $bill_master->createTime = $bill['createTime'];
        }

        if($pay_type_array['type'] == 1 && isset($payment_array))
        {
            $bill_master->payment_method_id =  $payment_array[0]['id'];
            $bill_master->payment_method_name = $payment_array[0]['name'];

        }
        $bill_master->bill_no = $bill_no;
        $bill_master->bill_code = $bill_code;
        $bill_master->pcustID = $customer_array['pcustID'];
        $bill_master->custID = $customer_array['custID'];
        $bill_master->bill_status = 0 ;//状态已确认
        $bill_master->billPromotion = $bill['billPromotion'];

        $bill_master->bill_totalMoney = $bill_totalMoney;
        $bill_master->bill_totalPoints = round($bill_money / 4);
        $bill_master->bill_accessories_money = $bill_accessories_money;
        $bill_master->bill_paying_agent_money = $bill_paying_agent_money;
        $bill_master->bill_subtract_money = $bill_subtract_money;
        $bill_master->bill_coupon_money = $bill_coupon_money;
        $bill_master->bill_pointsPrice = 0;
        $bill_master->bill_money = $bill_totalPaid;  //add by junhui.li 2015-06-16  订单金额=订单商品实际成交金额
        $bill_master->bill_totalPaid = $bill_totalPaid;
        $bill_master->bill_card_money = $bill_card_money;
        $bill_master->bill_balance_money = $bill_balance_money;
        $bill_master->bill_points_money = $bill_points_money;
        $bill_master->bill_online_money = $bill_online_money;
        $bill_master->bill_receivable_money = $bill_receivable_money;
        $bill_master->bill_received_money = $bill_money - $bill_receivable_money;

        $bill_master->deliverid = $deliver_array['deliverID'];
        $bill_master->deliver_name = encryptD($deliver_array['custName']);
        $bill_master->deliver_province = $deliver_array['provinceName'];
        $bill_master->deliver_provinceid = $deliver_array['provinceid'];
        $bill_master->deliver_city = $deliver_array['cityName'];
        $bill_master->deliver_cityid = $deliver_array['cityid'];
        $bill_master->deliver_county = $deliver_array['countyName'];
        $bill_master->deliver_countyid = $deliver_array['countyid'];
        $bill_master->deliver_address = encryptD($deliver_array['address']);
        $bill_master->deliver_mobile = encryptD($deliver_array['mobile']);
        $bill_master->deliver_phone = encryptD($deliver_array['phone']);
        $bill_master->send_date = $bill['send_date'];
        $bill_master->send_start_time = $bill['send_start_time'];
        $bill_master->send_end_time = $bill['send_end_time'];
        if (isset($distribution_array)) {
            $bill_master->distribution_id = $distribution_array[0]['distribution_id'];
            $bill_master->distribution_name = $distribution_array[0]['distribution_name'];
        }
        if (isset($distribution_technicia_array)) {
            $bill_master->distribution_technician_id = $distribution_technicia_array[0]['distribution_technician_id'];
            $bill_master->distribution_technicia = $distribution_technicia_array[0]['distribution_technicia'];
        }
        $bill_master->sendTypeID = $sendType_array[0]['sendTypeID'];
        $bill_master->sendTypeName = $sendType_array[0]['sendTypeName'];
        $bill_master->send_region_id = $send_area_array[0]['send_region_id'];
        $bill_master->send_region_name = $send_area_array[0]['send_region_name'];
        $bill_master->pay_type = $pay_type_array['type'];
        $bill_master->payTypeID = $pay_type_array['payTypeID'];
        $bill_master->payTypeName = $pay_type_array['payTypeName'];
        $bill_master->pay_status = $pay_status;
        $bill_master->remark = $bill['remark'];
        $bill_master->billPlatform = 3;
        $bill_master->billChannel = $bill['billChannel'];
        $bill_master->billType = $bill['billType'];
//        if ($bill['invoice_title_type']) {
//            $bill_master->invoice = 1;
//            $bill_master->invoiceID = $invoice_array['invoiceID'];
//        } else {
        $bill_master->invoice = 0;
        $bill_master->invoiceID = 0;
        //   }
        $bill_master->invoice_type = 1;
        $bill_master->invoice_title_type = $bill['invoice_title_type'];
        $bill_master->invoice_title = $bill['invoice_title'];
        $bill_master->invoice_content = $bill['invoice_content'];
        $bill_master->invoice_amount = $bill['invoice_amount'];
        $bill_master->invoice_number = $bill['invoice_number'];
        $bill_master->is_the_invoice = $bill['is_the_invoice'];
        $bill_master->is_urgent = $bill['is_urgent'];
        $bill_master->external_bill_no = $bill['external_bill_no'];
        $bill_master->bill_totalAmount = $bill_totalAmount;
        $bill_master->deliver_fee = $deliver_fee;
        $bill_master->deliver_feePaid = $deliver_feePaid;
        $bill_master->tableware_amount = $tableware_amount;
        $bill_master->candle_amount = $candle_amount;
        $bill_master->pay_name_str = implode(',', $temp_array['pay_name']);
        $bill_master->pay_id_str = implode(',', $temp_array['pay_id']);
        $bill_master->goods_name_str = implode(',', $temp_array['goods']);
        $bill_master->coupon_code = implode(',', $temp_array['coupon_code']);
        $bill_master->card_code = implode(',', $temp_array['card_code']);
        $bill_master->paying_agent_str = implode(',', $temp_array['paying_agent_str']);

        //保存反转的订单号，用于查询订单时，部分订单号HIT索引
        $bill_master->bill_code_reverse = strrev($bill_code);

//
        /**
         * 内部留言
         */
//        $bill_remark_array = array();
//        if (isset($bill['remark']) && !empty($bill['remark'])) {
//
//            foreach($bill['remark'] as &$remark) {
//                $bill_remark_obj = new entity('bill_remark');
//                $bill_remark_obj->creator = $bill['custID'];
//                $bill_remark_obj->createTime = $remark['createTime'];
//                $bill_remark_obj->bill_no = $bill_no;
//                $bill_remark_obj->remark = $remark['remark'];
//                $bill_remark_array[] = $bill_remark_obj;
//            }
//
//        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            //保存订单主表
            $G_SHOP->DBCA->save($bill_master);


//            //保存订单商品
            foreach($bill_goods_array as &$goods_obj) {

                if ($bill_master->bill_status > 0) {

                    $bill_goods_product = new entity('bill_goods_product');
                    $bill_goods_product->timeStamp = $G_SHOP->sys_datetime;
                    $bill_goods_product->creator = $bill['custID'];
                    $bill_goods_product->createTime = $G_SHOP->sys_datetime;
                    $bill_goods_product->bill_no = $goods_obj->bill_no;
                    $bill_goods_product->bill_goods_no = $goods_obj->bill_goods_no;
                    $bill_goods_product->bill_code = $bill_master->bill_code;
                    $bill_goods_product->cityID = $bill_master->deliver_cityid;
                    $bill_goods_product->cityName = $bill_master->deliver_city;
                    $bill_goods_product->billType = $bill_master->billType;
                    $bill_goods_product->send_date = $bill_master->send_date;
                    $bill_goods_product->send_start_time = $bill_master->send_start_time;
                    $bill_goods_product->send_end_time = $bill_master->send_end_time;
                    $bill_goods_product->distribution_id = $bill_master->distribution_id;
                    $bill_goods_product->distribution_name = $bill_master->distribution_name;
                    $bill_goods_product->is_urgent = $bill_master->is_urgent;
                    $bill_goods_product->goods_postID = $goods_obj->goods_postID;
                    $bill_goods_product->product_code = $goods_obj->product_code;
                    $bill_goods_product->goods_name = $goods_obj->goods_name;
                    $bill_goods_product->goods_spec = $goods_obj->goods_spec;
                    $bill_goods_product->goods_amount = $goods_obj->goods_amount;
                    $bill_goods_product->tableware_amount = $goods_obj->tableware_amount;
                    $bill_goods_product->extra_tableware_amount = $goods_obj->extra_tableware_amount;
                    $bill_goods_product->candle_amount = $goods_obj->candle_amount;
                    $bill_goods_product->extra_candle_amount = $goods_obj->extra_candle_amount;
                    $bill_goods_product->birthday_card = $goods_obj->birthday_card;
                    $bill_goods_product->segmentation = $goods_obj->segmentation;
                    $bill_goods_product->goods_remark = $goods_obj->goods_remark;
                    $G_SHOP->DBCA->save($bill_goods_product);

                }

                $G_SHOP->DBCA->save($goods_obj);


            }

            foreach($bill_goods_fittings_array as &$fit_obj) {
                $G_SHOP->DBCA->save($fit_obj);
            }

            //保存订单支付
            foreach($bill_pay_array as &$pay_obj) {
                $G_SHOP->DBCA->save($pay_obj);
            }

//            if (!empty($bill_remark_array)) {
//                foreach($bill_remark_array as &$remark_obj) {
//                    $G_SHOP->DBCA->save($remark_obj);
//                }
//            }



            $G_SHOP->DBCA->commit();

            return array(
                'code' => 200,
                'message' => 'ok',
                'bill_no' => $bill_no,
                'bill_code' => $bill_code
            );
        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array(
                    'code' => $e->getCode(),
                    'message' => $e->getMessage()
                );

            } else {
                error_log($e->getMessage());
                return array(
                    'code' => 500,
                    'message' => '系统错误'
                );
            }

        }

    }

    /*
     * add by Jerry 撒娇订单创建
     * 2015-04-23
     * */
    public function create_coquetry_bill( $bill ) {//,$config_array
        global $G_SHOP;

        $price_money=0;
        $info=$G_SHOP->sessionCache_get('info_ct_text');
        foreach($info as $goodsCode){
            foreach($goodsCode as $key=>$goodsCode1){
                foreach($goodsCode1 as $goodsCode2){

                    for($num = 1; $num<=$goodsCode2['num'];$num++)
                    {
                        $goods_array[] = array(
                            'sku' => $goodsCode2['code'],
                            'num' => 1
                        );

                    }
                }
                $packageSql="select package_price from  dunch_package  where package_id=?";

                $packageQuest=$G_SHOP->DBCA->stmt_query($packageSql,'s',$key);

                $price_money+=$packageQuest[0]->package_price*$goodsCode2['num'];


            }

        }


//        error_log(print_r($goods_array,1));
        //$bill['deliver_mobile']
        $bill['deliver_provinceid'] = 10; //省
        $bill['deliver_cityid'] = 110;  //市
        //$bill['country']

        //$bill['deliver_name']
        //$bill['deliver_address']
        //$bill['deliver_mobile']

        $bill['invoice_type'] = 1; //发票类型： 1、商业零售发票
        //$bill['invoice_title_type'] //1：个人 2：单位
        //$bill['invoice_title'] //发票抬头
        $bill['invoice_content'] = null;//发票内容
        $bill['invoice_amount'] = 1; //发票金额
        $bill['invoice_number'] = null;//发票号
        $bill['is_the_invoice']=0;  //是否开票 1、是 0、否
        $bill['is_urgent'] = 3;


        //$bill['payTypeID']
        //$bill['payment_method_id']

        //$bill['send_date']
        //$bill['send_start_time']
        //$bill['send_end_time']

        $bill['remark'] = '';
        $bill['billChannel'] = 1;
        $bill['billType'] = 1;

        //$bill['billPromotion']
        $bill['external_bill_no'] = null;



        quanli_require('module/base/customer/quanliCust.class.php');
        quanli_require('module/base/customer/custDeliver.class.php');
        quanli_require('module/base/customer/custInvoice.class.php');
        quanli_require('module/base/system/sysRegion.class.php');
        quanli_require('module/base/system/sysDistribution.class.php');
        quanli_require('module/base/system/sysDistributionTechnician.class.php');
        quanli_require('module/base/system/sysPayment.class.php');
        quanli_require('module/base/bill/billCheckout.class.php');
        quanli_require('module/base/bill/billSearch.class.php');
        quanli_require('module/base/system/sysSend.class.php');
        quanli_require('module/base/goods/quanliGoods.class.php');
        quanli_require('module/base/goods/goodsFittings.class.php');
        quanli_require('module/base/promotion/quanliCoupon.class.php');
        quanli_require('module/base/promotion/quanliCard.class.php');


        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        $quanliCust = new quanliCust();
        $custDeliver = new custDeliver();
        $custInvoice = new custInvoice();
        $sysDistribution = new sysDistribution();
        $sysPayment = new sysPayment();
        $billCheckout = new billCheckout();
        $sysSend = new sysSend();
        $sysRegion = new sysRegion( $G_SHOP->DBCA );




        /**
         * ==============================
         * 查询会员信息（如不存在则新建）
         * ==============================
         */


//        if(!isset($bill['deliver_mobile']) || empty($bill['deliver_mobile']))
//        {
//            return array('code'=>404,'message'=>'请输入');
//        }

        $args_array = array(
            'custID' => $bill['custID']
        );
        $customer_array = $quanliCust->searchCustomerDetail( $args_array );
        if (!$customer_array) {
            return array('code'=>404,'message'=>'会员信息不存在,请先注册');
        }
        /**
         * =====================
         * 省市区查询
         * =====================
         */
        $args_array = array(
            'id' => $bill['deliver_provinceid'],
            'region_level' => 1
        );
        $province_array = $sysRegion->getAreaManageList( $args_array );
        $args_array = array(
            'id' => $bill['deliver_cityid'],
            'region_level' => 2
        );
        $city_array = $sysRegion->getAreaManageList( $args_array );
        $args_array = array(
            'id' => $bill['country'],
            'region_level' => 3
        );
        $county_array = $sysRegion->getAreaManageList( $args_array );


        /**
         * ================
         * 收货地址
         * ================
         */
        $args_array = array(
            'pcustID' => $customer_array['pcustID'],
            'creator' => $bill['custID'],
            'custName' => $bill['deliver_name'],
            'provinceid' => $province_array[0]['id'],
            'cityid' => $city_array[0]['id'],
            'countyid' => $county_array[0]['id'],
            'address' => $bill['deliver_address'],
            'mobile' => $bill['deliver_mobile'],
            'phone' => ''
        );



        $deliver_array_s = $custDeliver->searchCustDeliver( $args_array );


        if($deliver_array_s)
        {
            $deliver_array = $deliver_array_s[0];
        }
        else
        {
            $result_deliver = $custDeliver->editCustDeliver( $args_array );
            $dunch_address=new entity("dunch_address");
            $dunch_address->pcustID=$result_deliver['data']['pcustID'];
            $dunch_address->deliverID=$result_deliver['data']['deliverID'];
            $G_SHOP->DBCA->save($dunch_address);
            if ($result_deliver['code'] != 200) {
                return $result_deliver;
            }
            else
            {
                $deliver_array = $result_deliver['data'];
            }
        }

        /**
         * ================
         * 查询配送站
         * ================
         */
        $areaID = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 1,463);//测试环境458 正式463


        if($areaID['areaID'] == 0)
        {
            //delete deliverID
            $sql_deleteDeliver = 'delete from dunch_address where deliverID='.$deliver_array['deliverID'];
            $G_SHOP->DBCA->stmt_query($sql_deleteDeliver);
            //return array('code'=>404,'message'=>print_r($areaID,1));
            return array('code'=>404,'message'=>'抱歉，该地址不在配送区域内!');
        }


        //查询地图区域和配送站的映射关系
        $args_array = array(
            'areaID' => $areaID['areaID']
        );
        $distribution_map_area = $sysDistribution->searchDistributionMapArea( $args_array );
        if($distribution_map_area) {
            $distribution_id = $distribution_map_area[0]['distribution_id'];
        }

        if (isset($distribution_id)) {
            //查询配送站
            $args_array = array(
                'distribution_id' => $distribution_id,
                'useFlg' => 1
            );
            $distribution_array = $sysDistribution->search( $args_array );
        }

        /**
         * ================
         * 查询配送方式
         * ================
         */
        $result_array = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 2,463);//测试环境458 正式463
        //error_log(print_r($result_array,1));
        $areaID = $result_array['areaID'];
        if ($areaID == 0) {
            $areaID = $result_array['default_areaID'];
        }
//
        //查询地图区域下的所有配送区域
        $args_array = array(
            'areaID' => $areaID
        );
        $send_area_array = $sysSend->searchSendArea( $args_array );
        if (!$send_area_array) {
            return $send_area_array;
        }
//
        //根据配送区域查询配送方式
        $args_array = array(
            'sendTypeID' => $send_area_array[0]['sendTypeID']
        );
        $sendType_array = $sysSend->searchSendType( $args_array );

        if($send_area_array[0]['freight'] > 0)
        {
            return array('code'=>404,'message'=>'抱歉，该地址不在配送区域内!');
        }





        $bill_no = generate_seqno('seqno_bill');
        $bill_code = $city_array[0]['alias'] . get_bill_code( 'seqno_bill_code' . $city_array[0]['alias'] );

        /**
         * ================
         * 查询支付方式
         * ================
         */
        $pay_type_array = null;
        /*$pay_type_array = $sysPayment->searchPayTypeDetail( $bill['payTypeID'] );

        if (!$pay_type_array) {
            return $pay_type_array;
        }

        if ($pay_type_array['type'] == 1 ) {
            if (!isset($bill['payment_method_id']) || !quanli_is_int($bill['payment_method_id'])) {
                return array('code'=>404,'message'=>'支付方式不存在');
            }
            $args_array = array(
                'id' => $bill['payment_method_id']
            );


            $payment_array = $sysPayment->searchPaymentMethod( $args_array );

            if (!$payment_array) {
                returnJsonData('支付方式不存在', 404);
            }
        }*/

//
        $bill_totalMoney = 0;//订单总金额,根据商品的标准售价计算出的，不含运费
        $bill_totalPaid = 0;//订单商品实际成交金额,不含运费，不含附加费
        $bill_accessories_money = 0; //订单配件金额
        $bill_subtract_money = 0; //订单立减金额
        $bill_coupon_money = 0; //订单优惠券订单金额
        $bill_card_money = 0; //代金卡抵扣金额
        $bill_paying_agent_money = 0; //代付订单总金额
        $bill_points_money = 0; //订单总积分价格??????
        $bill_balance_money = 0; //余额抵扣金额
        $bill_online_money = 0; //在线支付已付金额
        $deliver_fee = $send_area_array[0]['freight']; //运费
        $deliver_feePaid = $deliver_fee; //实收运费



//        if (isset($bill_data['bill_master']['deliver_feePaid']) && $bill_data['bill_master']['deliver_feePaid'] != '') {
//            $deliver_feePaid = $bill_data['bill_master']['deliver_feePaid']; //实收运费
//        } else {
//            $deliver_feePaid = $send_area_array[0]['freight']; //实收运费
//        }
        $bill_totalAmount = 0;
//
//
        //临时数组
        $temp_array = array(
            'pay_id' => array(),
            'pay_name' => array(),
            'goods' => array(),
            'coupon_code' => array(),
            'card_code' => array(),
            'paying_agent_str' => array()
        );


        /**
         * ===================
         * 订单商品
         * ===================
         */
        $bill_goods_array = array();

        $bill_goods_fittings_array = array();

        $tableware_amount = 0;

        $candle_amount = 0;

        //区分饮品还是蛋糕 start
        $sys_item_sql = 'SELECT * FROM sys_item WHERE itemCategoryID=36';
        $sys_item_data = &$G_SHOP->DBCA->stmt_query($sys_item_sql);

        $avgPrice=$this->calculationData($price_money,count($goods_array)/2);

        $goods_array=$this->avgPriceArray($sys_item_data,$goods_array,$avgPrice);



        //区分饮品还是蛋糕 end

        foreach($goods_array as &$goods) {

            $args_array = array(
                'product_code' => $goods['sku'],
            );
            $goods_info = $quanliGoods->searchGoodsSaleDetail( $args_array );
            if (!$goods_info) {
                return  array(
                    'code' => 404,
                    'message' => '没有商品' . $goods['sku']
                );
            }

            $bill_goods_obj = new entity('bill_goods');
            $bill_goods_obj->creator = $bill['custID'];
            $bill_goods_obj->bill_no = $bill_no;
            $bill_goods_obj->bill_goods_no = generate_seqno('seqno_bill_goods');
            $bill_goods_obj->goods_goodsID = $goods_info['goodsID'];
            $bill_goods_obj->goods_postID = $goods_info['postID'];
            $bill_goods_obj->product_code = $goods_info['product_code'];
            $bill_goods_obj->goods_name = $goods_info['goodsName'];
            $bill_goods_obj->goods_spec = $goods_info['spec'];
            $bill_goods_obj->goods_amount = $goods['num'];
            $bill_goods_obj->goods_marketPrice = $goods_info['marketPrice'];
            $bill_goods_obj->goods_storePrice = $goods_info['salePrice'];
            //add by junhui.li 20150609 订单金额优化 start
            //$bill_goods_obj->goods_purchasePrice = $goods_info['salePrice'];
            $bill_goods_obj->goods_purchasePrice = $goods['coffeePrice'];
            //add by junhui.li 20150609 订单金额优化 end
            $bill_goods_obj->goods_pointsPrice = 0;
            $bill_goods_obj->goods_points = 0;
            $bill_goods_obj->goods_weight = 0;
            $bill_goods_obj->goods_from = 1;
            $bill_goods_obj->goods_groupID = 0;
            $bill_goods_obj->goods_remark = isset($goods['goods_remark']) ? $goods['goods_remark'] : null;
            $bill_goods_obj->birthday_card = isset($goods['birthday_card']) ? $goods['birthday_card'] : null;
            $bill_goods_obj->segmentation = isset($goods['segmentation']) ? $goods['segmentation'] : 0;
            $bill_goods_array[] = $bill_goods_obj;
            $bill_totalAmount++;

            $bill_totalMoney += $bill_goods_obj->goods_storePrice;
            $bill_totalPaid += $bill_goods_obj->goods_purchasePrice;
            $temp_array['goods'][] =  $goods_info['goodsName'];




        }
        //订单金额
        $bill_money = $price_money;

        //订单应收金额
        $bill_receivable_money = $price_money;


        $bill_pay_array = array();


        //保存订单支付信息
        $pay_status = 0;
        if ($bill_receivable_money >= 0) {

            if ($bill_receivable_money == 0) {
                $pay_status = 2;
            }

            $bill_pay_obj = new entity('bill_pay');
            $bill_pay_obj->creator = $bill['custID'];
            $bill_pay_obj->bill_no = $bill_no;

            //支付方式隐藏！！！！！
            /*$bill_pay_obj->payTypeID = $pay_type_array['payTypeID'];
            $bill_pay_obj->payTypeName = $pay_type_array['payTypeName'];
            $bill_pay_obj->type = $pay_type_array['type'];
            $bill_pay_obj->pay_amount = $bill_receivable_money;
            if ($pay_type_array['type'] == 1) {
                $bill_pay_obj->deduct_amount = 0;
                $bill_pay_obj->payment_method_id = $payment_array[0]['id'];

                $bill_pay_obj->payment_method_name = $payment_array[0]['name'];
                $bill_pay_obj->payment_method_type = $payment_array[0]['type'];


            } else {
                $bill_pay_obj->deduct_amount = 0;
            }

            $bill_pay_array[] = $bill_pay_obj;

            $temp_array['pay_id'][] = $pay_type_array['payTypeID'];
            $temp_array['pay_name'][] = $pay_type_array['payTypeName'];
            */

        }

        $bill_master = new entity('bill_master');
        $bill_master->creator = $bill['custID'];
        if (!empty($bill['createTime'])) {
            $bill_master->createTime = $bill['createTime'];
        }

        if($pay_type_array['type'] == 1 && isset($payment_array))
        {
            $bill_master->payment_method_id =  $payment_array[0]['id'];
            $bill_master->payment_method_name = $payment_array[0]['name'];
        }
        $bill_master->bill_no = $bill_no;
        $bill_master->bill_code = $bill_code;
        $bill_master->pcustID = $customer_array['pcustID'];
        $bill_master->custID = $customer_array['custID'];
        $bill_master->bill_status = 0 ;//状态已确认
        $bill_master->billPromotion = $bill['billPromotion'];

        $bill_master->bill_totalMoney = $bill_totalMoney;
        $bill_master->bill_totalPoints = round($bill_money / 4);
        $bill_master->bill_accessories_money = $bill_accessories_money;
        $bill_master->bill_paying_agent_money = $bill_paying_agent_money;
        $bill_master->bill_subtract_money = $bill_subtract_money;
        $bill_master->bill_coupon_money = $bill_coupon_money;
        $bill_master->bill_pointsPrice = 0;
        $bill_master->bill_money = $bill_totalPaid;//add by junhui.li 2015-06-16  订单金额=订单商品实际成交金额
        $bill_master->bill_totalPaid = $bill_totalPaid;
        $bill_master->bill_card_money = $bill_card_money;
        $bill_master->bill_balance_money = $bill_balance_money;
        $bill_master->bill_points_money = $bill_points_money;
        $bill_master->bill_online_money = $bill_online_money;
        $bill_master->bill_receivable_money = $bill_receivable_money;
        $bill_master->bill_received_money = $bill_money - $bill_receivable_money;

        $bill_master->deliverid = $deliver_array['deliverID'];
        $bill_master->deliver_name = encryptD($deliver_array['custName']);
        $bill_master->deliver_province = $deliver_array['provinceName'];
        $bill_master->deliver_provinceid = $deliver_array['provinceid'];
        $bill_master->deliver_city = $deliver_array['cityName'];
        $bill_master->deliver_cityid = $deliver_array['cityid'];
        $bill_master->deliver_county = $deliver_array['countyName'];
        $bill_master->deliver_countyid = $deliver_array['countyid'];
        $bill_master->deliver_address = encryptD($deliver_array['address']);
        $bill_master->deliver_mobile = encryptD($deliver_array['mobile']);
        $bill_master->deliver_phone = encryptD($deliver_array['phone']);
        $bill_master->send_date = $bill['send_date'];
        $bill_master->send_start_time = $bill['send_start_time'];
        $bill_master->send_end_time = $bill['send_end_time'];
        if (isset($distribution_array)) {
            $bill_master->distribution_id = $distribution_array[0]['distribution_id'];
            $bill_master->distribution_name = $distribution_array[0]['distribution_name'];
        }
        if (isset($distribution_technicia_array)) {
            $bill_master->distribution_technician_id = $distribution_technicia_array[0]['distribution_technician_id'];
            $bill_master->distribution_technicia = $distribution_technicia_array[0]['distribution_technicia'];
        }
        $bill_master->sendTypeID = $sendType_array[0]['sendTypeID'];
        $bill_master->sendTypeName = $sendType_array[0]['sendTypeName'];
        $bill_master->send_region_id = $send_area_array[0]['send_region_id'];
        $bill_master->send_region_name = $send_area_array[0]['send_region_name'];
        $bill_master->pay_type = $pay_type_array['type'];
        $bill_master->payTypeID = $pay_type_array['payTypeID'];
        $bill_master->payTypeName = $pay_type_array['payTypeName'];
        $bill_master->pay_status = $pay_status;
        $bill_master->remark = $bill['remark'];
        $bill_master->billPlatform = 3;
        $bill_master->billChannel = $bill['billChannel'];
        $bill_master->billType = $bill['billType'];
//        if ($bill['invoice_title_type']) {
//            $bill_master->invoice = 1;
//            $bill_master->invoiceID = $invoice_array['invoiceID'];
//        } else {
        $bill_master->invoice = 0;
        $bill_master->invoiceID = 0;
        //   }
        $bill_master->invoice_type = 1;
        $bill_master->invoice_title_type = $bill['invoice_title_type'];
        $bill_master->invoice_title = $bill['invoice_title'];
        $bill_master->invoice_content = $bill['invoice_content'];
        $bill_master->invoice_amount = $bill['invoice_amount'];
        $bill_master->invoice_number = $bill['invoice_number'];
        $bill_master->is_the_invoice = $bill['is_the_invoice'];
        $bill_master->is_urgent = $bill['is_urgent'];
        $bill_master->external_bill_no = $bill['external_bill_no'];
        $bill_master->bill_totalAmount = $bill_totalAmount;
        $bill_master->deliver_fee = $deliver_fee;
        $bill_master->deliver_feePaid = $deliver_feePaid;
        $bill_master->tableware_amount = $tableware_amount;
        $bill_master->candle_amount = $candle_amount;
        //支付方式隐藏！！！！
        /*
        $bill_master->pay_name_str = implode(',', $temp_array['pay_name']);
        $bill_master->pay_id_str = implode(',', $temp_array['pay_id']);
*/
        $bill_master->goods_name_str = implode(',', $temp_array['goods']);
        $bill_master->coupon_code = implode(',', $temp_array['coupon_code']);
        $bill_master->card_code = implode(',', $temp_array['card_code']);
        $bill_master->paying_agent_str = implode(',', $temp_array['paying_agent_str']);
        //保存反转的订单号，用于查询订单时，部分订单号HIT索引
        $bill_master->bill_code_reverse = strrev($bill_code);

        try {

            $G_SHOP->DBCA->beginTransaction();

            //保存订单主表
            $G_SHOP->DBCA->save($bill_master);



//            //保存订单商品
            foreach($bill_goods_array as &$goods_obj) {

                if ($bill_master->bill_status > 0) {

                    $bill_goods_product = new entity('bill_goods_product');
                    $bill_goods_product->timeStamp = $G_SHOP->sys_datetime;
                    $bill_goods_product->creator = $bill['custID'];
                    $bill_goods_product->createTime = $G_SHOP->sys_datetime;
                    $bill_goods_product->bill_no = $goods_obj->bill_no;
                    $bill_goods_product->bill_goods_no = $goods_obj->bill_goods_no;
                    $bill_goods_product->bill_code = $bill_master->bill_code;
                    $bill_goods_product->cityID = $bill_master->deliver_cityid;
                    $bill_goods_product->cityName = $bill_master->deliver_city;
                    $bill_goods_product->billType = $bill_master->billType;
                    $bill_goods_product->send_date = $bill_master->send_date;
                    $bill_goods_product->send_start_time = $bill_master->send_start_time;
                    $bill_goods_product->send_end_time = $bill_master->send_end_time;
                    $bill_goods_product->distribution_id = $bill_master->distribution_id;
                    $bill_goods_product->distribution_name = $bill_master->distribution_name;
                    $bill_goods_product->is_urgent = $bill_master->is_urgent;
                    $bill_goods_product->goods_postID = $goods_obj->goods_postID;
                    $bill_goods_product->product_code = $goods_obj->product_code;
                    $bill_goods_product->goods_name = $goods_obj->goods_name;
                    $bill_goods_product->goods_spec = $goods_obj->goods_spec;
                    $bill_goods_product->goods_amount = $goods_obj->goods_amount;
                    $bill_goods_product->tableware_amount = $goods_obj->tableware_amount;
                    $bill_goods_product->extra_tableware_amount = $goods_obj->extra_tableware_amount;
                    $bill_goods_product->candle_amount = $goods_obj->candle_amount;
                    $bill_goods_product->extra_candle_amount = $goods_obj->extra_candle_amount;
                    $bill_goods_product->birthday_card = $goods_obj->birthday_card;
                    $bill_goods_product->segmentation = $goods_obj->segmentation;
                    $bill_goods_product->goods_remark = $goods_obj->goods_remark;
                    $G_SHOP->DBCA->save($bill_goods_product);

                }

                $G_SHOP->DBCA->save($goods_obj);

            }

            //保存配件！！！
            /*foreach($bill_goods_fittings_array as &$fit_obj) {
                $G_SHOP->DBCA->save($fit_obj);
            }*/

            //保存订单支付！！！！
            /*foreach($bill_pay_array as &$pay_obj) {
                $G_SHOP->DBCA->save($pay_obj);
            }*/

//            if (!empty($bill_remark_array)) {
//                foreach($bill_remark_array as &$remark_obj) {
//                    $G_SHOP->DBCA->save($remark_obj);
//                }
//            }


            $G_SHOP->DBCA->commit();

            return array(
                'code' => 200,
                'message' => 'ok',
                'bill_no' => $bill_no,
                'bill_code' => $bill_code
            );
        } catch (Exception $e) {
            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array(
                    'code' => $e->getCode(),
                    'message' => $e->getMessage()
                );

            } else {
                error_log($e->getMessage());
                return array(
                    'code' => 500,
                    'message' => '系统错误'
                );
            }

        }

    }


    public function searchBillDetail(&$arg_array)
    {
        global $G_SHOP;
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //sql字符串
        $sql = 'WHERE 1 = 1 ';

        //套餐名称
        if (isset($arg_array['bill_no']) && !empty($arg_array['bill_no'])) {
            $sql .= ' AND bill_no = ?';
            $params_type .= 's';
            $params_array[] =  $arg_array['bill_no'];

        }



        //查询订单商品信息
        $search_sql = 'SELECT * FROM dunch_bill_detail ' . $sql;
        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
        if (!$temp_item_array) {
            return null;
        }



        $item_array = array();
        foreach ($temp_item_array as &$item) {
            $item_array[] = array(
                'bill_no' => $item->bill_no,
                'bill_code' => $item->bill_code,
                'package_id' => $item->package_id,
                'package_name' => $item->package_name,
                'goods_id_str' => $item->goods_id_str,
                'goods_name_str' => $item->goods_name_str,
                'buy_amount' => $item->buy_amount
            );
        }
        return $item_array;
    }


    //创建下午茶我要请客订单
    public function create_treat_bill( $bill ) {

        global $G_SHOP;

        //$price_money=0;

        $bill['deliver_provinceid'] = 10; //省
        $bill['deliver_cityid'] = 110;  //市

        $bill['invoice_type'] = 1; //发票类型： 1、商业零售发票
        //$bill['invoice_title_type'] //1：个人 2：单位
        //$bill['invoice_title'] //发票抬头
        $bill['invoice_content'] = null;//发票内容
        $bill['invoice_amount'] = 1; //发票金额
        $bill['invoice_number'] = null;//发票号
        $bill['is_the_invoice']=0;  //是否开票 1、是 0、否
        $bill['is_urgent'] = 3;


        $bill['remark'] = '';
        $bill['billChannel'] = 1;
        $bill['billType'] = 1;

        $bill['external_bill_no'] = null;


        quanli_require('module/base/customer/quanliCust.class.php');
        quanli_require('module/base/customer/custDeliver.class.php');
        quanli_require('module/base/customer/custInvoice.class.php');
        quanli_require('module/base/system/sysRegion.class.php');
        quanli_require('module/base/system/sysDistribution.class.php');
        quanli_require('module/base/system/sysDistributionTechnician.class.php');
        quanli_require('module/base/system/sysPayment.class.php');
        quanli_require('module/base/bill/billCheckout.class.php');
        quanli_require('module/base/bill/billSearch.class.php');
        quanli_require('module/base/system/sysSend.class.php');
        quanli_require('module/base/goods/quanliGoods.class.php');
        quanli_require('module/base/goods/goodsFittings.class.php');
        quanli_require('module/base/promotion/quanliCoupon.class.php');
        quanli_require('module/base/promotion/quanliCard.class.php');


        //$quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        $quanliCust = new quanliCust();
        $custDeliver = new custDeliver();
        $custInvoice = new custInvoice();
        $sysDistribution = new sysDistribution();
        $sysPayment = new sysPayment();
        $billCheckout = new billCheckout();
        $sysSend = new sysSend();
        $sysRegion = new sysRegion( $G_SHOP->DBCA );


        /**
         * ==============================
         * 查询会员信息（如不存在则新建）
         * ==============================
         */

        $args_array = array(
            'custID' => $bill['custID']
        );
        $customer_array = $quanliCust->searchCustomerDetail( $args_array );

        if (!$customer_array) {
            return array('code'=>404,'message'=>'会员信息不存在,请先注册');

        }

        /**
         * =====================
         * 省市区查询
         * =====================
         */

        $args_array = array(
            'id' => $bill['deliver_provinceid'],
            'region_level' => 1
        );
        $province_array = $sysRegion->getAreaManageList( $args_array );
        $args_array = array(
            'id' => $bill['deliver_cityid'],
            'region_level' => 2
        );
        $city_array = $sysRegion->getAreaManageList( $args_array );
        $args_array = array(
            'id' => $bill['country'],
            'region_level' => 3
        );
        $county_array = $sysRegion->getAreaManageList( $args_array );


        /**
         * ================
         * 收货地址
         * ================
         */
        $args_array = array(
            'pcustID' => $customer_array['pcustID'],
            'creator' => $bill['custID'],
            'custName' => $bill['deliver_name'],
            'provinceid' => $province_array[0]['id'],
            'cityid' => $city_array[0]['id'],
            'countyid' => $county_array[0]['id'],
            'address' => $bill['deliver_address'],
            'mobile' => $bill['deliver_mobile'],
            'phone' => ''
        );

        $deliver_array_s = $custDeliver->searchCustDeliver( $args_array );

        if($deliver_array_s)
        {
            $deliver_array = $deliver_array_s[0];
        }
        else
        {
            $result_deliver = $custDeliver->editCustDeliver( $args_array );
            $dunch_address=new entity("dunch_address");
            $dunch_address->pcustID=$result_deliver['data']['pcustID'];
            $dunch_address->deliverID=$result_deliver['data']['deliverID'];
            $G_SHOP->DBCA->save($dunch_address);
            if ($result_deliver['code'] != 200) {
                return $result_deliver;
            }
            else
            {
                $deliver_array = $result_deliver['data'];
            }
        }



        /**
         * ================
         * 查询配送站
         * ================
         */
        $areaID = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 1,463);//测试环境458 正式463


        if($areaID['areaID'] == 0)
        {
            //return array('code'=>404,'message'=>print_r($areaID,1));
            return array('code'=>404,'message'=>'抱歉该地址不属于配送区域!');
        }


        //查询地图区域和配送站的映射关系
        $args_array = array(
            'areaID' => $areaID['areaID']
        );
        $distribution_map_area = $sysDistribution->searchDistributionMapArea( $args_array );
        if($distribution_map_area) {
            $distribution_id = $distribution_map_area[0]['distribution_id'];
        }

        if (isset($distribution_id)) {
            //查询配送站
            $args_array = array(
                'distribution_id' => $distribution_id,
                'useFlg' => 1
            );
            $distribution_array = $sysDistribution->search( $args_array );
        }


        /**
         * ================
         * 查询配送方式
         * ================
         */
        $result_array = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 2,463);//测试环境458 正式463

        $areaID = $result_array['areaID'];
        if ($areaID == 0) {
            $areaID = $result_array['default_areaID'];
        }
//
        //查询地图区域下的所有配送区域
        $args_array = array(
            'areaID' => $areaID
        );
        $send_area_array = $sysSend->searchSendArea( $args_array );
        if (!$send_area_array) {
            return $send_area_array;
        }
//
        //根据配送区域查询配送方式
        $args_array = array(
            'sendTypeID' => $send_area_array[0]['sendTypeID']
        );
        $sendType_array = $sysSend->searchSendType( $args_array );

        if($send_area_array[0]['freight'] > 0)
        {
            return array('code'=>404,'message'=>'抱歉,该地址不属于配送区域!');
        }


        $bill_no = generate_seqno('seqno_bill');
        $bill_code = $city_array[0]['alias'] . get_bill_code( 'seqno_bill_code' . $city_array[0]['alias'] );

        /**
         * ================
         * 查询支付方式
         * ================
         */

        $pay_type_array = $sysPayment->searchPayTypeDetail( $bill['payTypeID'] );

        if (!$pay_type_array) {
            return $pay_type_array;
        }

        if ($pay_type_array['type'] == 1 ) {
            if (!isset($bill['payment_method_id']) || !quanli_is_int($bill['payment_method_id'])) {

                return array('code'=>404,'message'=>'支付方式不存在');
            }
            $args_array = array(
                'id' => $bill['payment_method_id']
            );
            $payment_array = $sysPayment->searchPaymentMethod( $args_array );

            if (!$payment_array) {
                returnJsonData('支付方式不存在', 404);
            }
        }
        $numIfo=$G_SHOP->sessionCache_get('numIfo');//获取session内的购买数量 免单数量 套餐销售日期
        $orderTotalNum=$numIfo['buyNum'];  //总套餐数 *
        $orderShakeNum=$numIfo['mnum'];   //摇到的数量 *
        $treatReason=$bill['teamark']; //请客理由*
        if($numIfo['buyNum']==''){
            returnJsonData('请重新下单', 400);
        }

        $numIfo['tdate'];//套餐销售日期
        $packageSql='SELECT b.package_price as package_price FROM  dunch_sale AS a JOIN dunch_package AS b ON  a.package_id=b.package_id WHERE sale_date= ?  LIMIT 1';
        $drawInfo=$G_SHOP->DBCA->stmt_query($packageSql,'s',$numIfo['tdate']);


        $bill_totalMoney = $orderTotalNum*$drawInfo[0]->package_price;//订单总金额,根据商品的标准售价计算出的，不含运费 数量*单价
        $bill_accessories_money = 0; //订单配件金额
        $bill_subtract_money = $orderShakeNum*$drawInfo[0]->package_price; //订单立减金额
        $bill_totalPaid = ($bill_totalMoney-$bill_subtract_money)> 0 ? ($bill_totalMoney-$bill_subtract_money) : 0;//订单商品实际成交金额,不含运费，不含附加费
        $bill_coupon_money = 0; //订单优惠券订单金额
        $bill_card_money = 0; //代金卡抵扣金额
        $bill_paying_agent_money = 0; //代付订单总金额
        $bill_points_money = 0; //订单总积分价格??????
        $bill_balance_money = 0; //余额抵扣金额
        $bill_online_money = 0; //在线支付已付金额

        $bill_totalAmount = $numIfo['buyNum']*2;

        //临时数组
        $temp_array = array(
            'pay_id' => array(),
            'pay_name' => array(),
            'goods' => array(),
            'coupon_code' => array(),
            'card_code' => array(),
            'paying_agent_str' => array()
        );



        //订单金额
        $bill_money = $bill_totalMoney;
        //订单应收金额
        $bill_receivable_money = $bill_totalPaid;
        $bill_pay_array = array();
        //保存订单支付信息
        $pay_status = 0;
        $bill_status=0;
        if ($bill_receivable_money >= 0) {

            if ($bill_receivable_money == 0) {
                $pay_status = 1;
                //订单金额==0 订单状态已确认
                $bill_status=1;

            }

            $bill_pay_obj = new entity('bill_pay');
            $bill_pay_obj->creator = $bill['custID'];
            $bill_pay_obj->bill_no = $bill_no;
            $bill_pay_obj->payTypeID = $pay_type_array['payTypeID'];
            $bill_pay_obj->payTypeName = $pay_type_array['payTypeName'];
            $bill_pay_obj->type = $pay_type_array['type'];
            $bill_pay_obj->pay_amount = $bill_receivable_money;
            if ($pay_type_array['type'] == 1) {
                $bill_pay_obj->deduct_amount = 0;
                $bill_pay_obj->payment_method_id = $payment_array[0]['id'];

                $bill_pay_obj->payment_method_name = $payment_array[0]['name'];
                $bill_pay_obj->payment_method_type = $payment_array[0]['type'];


            } else {
                $bill_pay_obj->deduct_amount = 0;
            }

            $bill_pay_array[] = $bill_pay_obj;

            $temp_array['pay_id'][] = $pay_type_array['payTypeID'];
            $temp_array['pay_name'][] = $pay_type_array['payTypeName'];

        }


        $bill_master = new entity('bill_master');
        $bill_master->creator = $bill['custID'];
        if (!empty($bill['createTime'])) {
            $bill_master->createTime = $bill['createTime'];
        }

        if($pay_type_array['type'] == 1 && isset($payment_array))
        {
            $bill_master->payment_method_id =  $payment_array[0]['id'];
            $bill_master->payment_method_name = $payment_array[0]['name'];

        }


        $bill_master->bill_no = $bill_no;
        $bill_master->bill_code = $bill_code;
        $bill_master->pcustID = $customer_array['pcustID'];
        $bill_master->custID = $customer_array['custID'];
        $bill_master->bill_status = $bill_status ;
        //$bill_master->billPromotion = $bill['billPromotion'];

        $bill_master->bill_totalMoney = $bill_totalMoney;
        $bill_master->bill_totalPoints = round($bill_money / 4);
        $bill_master->bill_accessories_money = $bill_accessories_money;
        $bill_master->bill_paying_agent_money = $bill_paying_agent_money;
        $bill_master->bill_subtract_money = $bill_subtract_money;
        $bill_master->bill_coupon_money = $bill_coupon_money;
        $bill_master->bill_pointsPrice = 0;
        $bill_master->bill_money = $bill_totalPaid;//add by junhui.li 2015-06-16  订单金额=订单商品实际成交金额
        $bill_master->bill_totalPaid = $bill_totalPaid;
        $bill_master->bill_card_money = $bill_card_money;
        $bill_master->bill_balance_money = $bill_balance_money;
        $bill_master->bill_points_money = $bill_points_money;
        $bill_master->bill_online_money = $bill_online_money;
        $bill_master->bill_receivable_money = $bill_receivable_money;
        $bill_master->bill_received_money = $bill_money - $bill_receivable_money;

        $bill_master->deliverid = $deliver_array['deliverID'];
        $bill_master->deliver_name = encryptD($deliver_array['custName']);
        $bill_master->deliver_province = $deliver_array['provinceName'];
        $bill_master->deliver_provinceid = $deliver_array['provinceid'];
        $bill_master->deliver_city = $deliver_array['cityName'];
        $bill_master->deliver_cityid = $deliver_array['cityid'];
        $bill_master->deliver_county = $deliver_array['countyName'];
        $bill_master->deliver_countyid = $deliver_array['countyid'];
        $bill_master->deliver_address = encryptD($deliver_array['address']);
        $bill_master->deliver_mobile = encryptD($deliver_array['mobile']);
        $bill_master->deliver_phone = encryptD($deliver_array['phone']);
        $bill_master->send_date = $bill['send_date'];
        $bill_master->send_start_time = $bill['send_start_time'];
        $bill_master->send_end_time = $bill['send_end_time'];

        if (isset($distribution_array)) {
            $bill_master->distribution_id = $distribution_array[0]['distribution_id'];
            $bill_master->distribution_name = $distribution_array[0]['distribution_name'];
        }
        if (isset($distribution_technicia_array)) {
            $bill_master->distribution_technician_id = $distribution_technicia_array[0]['distribution_technician_id'];
            $bill_master->distribution_technicia = $distribution_technicia_array[0]['distribution_technicia'];
        }

        $bill_master->pay_type = $pay_type_array['type'];
        $bill_master->payTypeID = $pay_type_array['payTypeID'];
        $bill_master->payTypeName = $pay_type_array['payTypeName'];
        $bill_master->pay_status = $pay_status;
        $bill_master->remark = $bill['remark'];
        $bill_master->billPlatform = 3;
        $bill_master->billChannel = $bill['billChannel'];
        $bill_master->billType = $bill['billType'];

        $bill_master->invoice = 0;
        $bill_master->invoiceID = 0;

        $bill_master->invoice_type = 1;

        $bill_master->invoice_content = $bill['invoice_content'];
        $bill_master->invoice_amount = $bill['invoice_amount'];
        $bill_master->invoice_number = $bill['invoice_number'];
        $bill_master->is_the_invoice = $bill['is_the_invoice'];
        $bill_master->is_urgent = $bill['is_urgent'];
        $bill_master->external_bill_no = $bill['external_bill_no'];
        $bill_master->bill_totalAmount = $bill_totalAmount;

        $bill_master->pay_name_str = implode(',', $temp_array['pay_name']);
        $bill_master->pay_id_str = implode(',', $temp_array['pay_id']);
        $bill_master->goods_name_str = implode(',', $temp_array['goods']);
        $bill_master->coupon_code = implode(',', $temp_array['coupon_code']);
        $bill_master->card_code = implode(',', $temp_array['card_code']);
        $bill_master->paying_agent_str = implode(',', $temp_array['paying_agent_str']);
        //保存反转的订单号，用于查询订单时，部分订单号HIT索引
        $bill_master->bill_code_reverse = strrev($bill_code);

        /**
         * 保存到dunch_treat
         * */
        $dunch_treat = new entity('dunch_treat');
        $dunch_treat->bill_no=$bill_no;     //订单号
        $dunch_treat->pcustID=$customer_array['pcustID'];     //会员号
        $dunch_treat->packageNumber=$orderTotalNum; //套餐数量
        $dunch_treat->freeNumber=$orderShakeNum;      //免杯数量
        $dunch_treat->treatReason=$treatReason;   //请客理由
        $dunch_treat->billMark=0;        //是否可生产标示  默认为0
        $dunch_treat->openid=$bill['wxopenid'];        //微信opendID
        $dunch_treat->nickname=$bill['wxnickname'];        //微信昵称
        $dunch_treat->headimgurl=$bill['wxheadimgurl'];        //微信头像
        $dunch_treat->sentStatus=1;        //是否发送短信1未发送，2已发送



        /**
         * 内部留言
         */
        try {

            $G_SHOP->DBCA->beginTransaction();
            //保存订单主表
            $resultSave=$G_SHOP->DBCA->save($bill_master);
            if($resultSave=1){
                $G_SHOP->DBCA->save($dunch_treat);
                if ($bill_receivable_money == 0) {
                    $pay_status = 2;
                    //订单金额==0 订单状态已确认
                    $bill_status=1;
                    //实例化下午茶操作类

                    $ddd=$this->toDraw($bill_no);


                    /*
                     * 推送微信图文消息end
                     */

                    //加载短信类
                    quanli_include('module/base/common/quanliSms.class.php');

                    //实例化短信类
                    $quanliSms = new quanliSms();
                    //查询短信内容
                    $billSql="select custID,bill_code,send_start_time,send_end_time,bill_totalAmount,bill_no from bill_master where bill_no=?";
                    $billQuest=$G_SHOP->DBCA->stmt_query($billSql,'s',$bill_no);
                    /**
                     * ============================
                     * 发送短信
                     * ============================
                     */
                    //生成短信内容
                    $data_array = array(
                        '$bill_code' => $billQuest[0]->bill_code,
                        '$num' =>$billQuest[0]->bill_totalAmount/2,
                        '$send_time' =>$billQuest[0]->send_start_time."-".$billQuest[0]->send_end_time,
                    );
                    $sms_content = $quanliSms->getSmsContent( 'dunch_treat_pay', $data_array );

                    //发送短信
                    $result_array = $quanliSms->sendSMS(  $billQuest[0]->custID, $sms_content );

                }
            }

            //保存订单支付
            foreach($bill_pay_array as &$pay_obj) {
                $G_SHOP->DBCA->save($pay_obj);
            }

            $G_SHOP->sessionCache_remove( 'numIfo' );
            $G_SHOP->DBCA->commit();

            return array(
                'code' => 200,
                'message' => 'ok',
                'bill_no' => $bill_no,
                'bill_code' => $bill_code
            );

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array(
                    'code' => $e->getCode(),
                    'message' => $e->getMessage()
                );

            } else {
                error_log($e->getMessage());
                return array(
                    'code' => 500,
                    'message' => '系统错误'
                );
            }

        }


    }
    //订单支付成功后推图文消息
    public function toDraw($bill_no){
        global $G_SHOP;
        //获取请客人微信ID  和 昵称
        $treatSql="select openid,nickname from dunch_treat where bill_no=?";
        $treatInfo=$G_SHOP->DBCA->stmt_query($treatSql,'s',$bill_no);
        $openID=$treatInfo[0]->openid;//微信OPENid
        $nickename=$treatInfo[0]->nickname;//昵称
        //查询订单的配送开始时间
        $dateSql="select send_date,send_start_time,bill_status from  bill_master where bill_no=?";
        $dateInfo=$G_SHOP->DBCA->stmt_query($dateSql,'s',$bill_no);
        $send_date=$dateInfo[0]->send_date;
        $send_start_time=$dateInfo[0]->send_start_time;
        $send_select_time= date("H:i:s",strtotime($send_start_time)-300);
       // $access_token=$this->getAccess_token('wxf346c8e83586af4c','aa36ea3b65cc4265d759813259720384');

        //查询access_token
//        $tokenSql="SELECT itemName FROM  sys_item WHERE  itemID=483";
//        $tokenInfo=$G_SHOP->DBCA->stmt_query($tokenSql);
        $access_token = $G_SHOP->eai('wdh')->getAccessToken();

        $tp='{
            "touser": "'.$openID.'",
            "msgtype": "news",
            "news": {
                "articles": [
                    {
                        "title": "【请客函】'.$nickename.'请你吃Mcake下午茶",
                        "description": "1、2、3，放空一下",
                        "url": "http:\/\/121.43.104.7\/dunch\/dunch_treat_select.html?bill_no='.$bill_no.'",
                        "picurl": "http:\/\/121.43.104.7\/dunch\/theme\/xth1\/images\/treat\/give.jpg"
                    }
                ]
            }
        }';

        $t='{
            "touser":"'.$openID.'",
            "msgtype":"text",
            "text":
            {
                 "content":"长按【请客函】，转发给你想请客的小伙伴，让他们来选下午茶套餐吧！套餐领取截止时间'.$send_date.' '.$send_select_time.'，请尽快哟，拜托了！"
            }
            }';


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $postJosnData);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $tp);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        $dd=json_decode($tmpInfo,true);

        if (curl_errno($ch)) {
            echo curl_error($ch);
        }
        curl_close($ch);


        $chd = curl_init();
        curl_setopt($chd, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token);
        curl_setopt($chd, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($chd, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($chd, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($chd, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($chd, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($chd, CURLOPT_AUTOREFERER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $postJosnData);
        curl_setopt($chd, CURLOPT_POSTFIELDS, $t);
        curl_setopt($chd, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo1 = curl_exec($chd);
        $dd1=json_decode($tmpInfo1,true);
        if (curl_errno($chd)) {
            echo curl_error($chd);
        }
        curl_close($chd);
        if($dd['errcode']==0){
            $title="微信消息推送:成功";
        }else{
            $title="微信消息推送:失败,".$dd['errcode'].",".$dd['errmsg'];
        }
        //订单推送图文日志start
        $log_detail=new entity("log_detail");
        $log_detail->creator="system";
        $log_detail->logCategoryID=1;
        $log_detail->logItem=$bill_no;
        $log_detail->extend_1=$title;
        $log_detail->extend_5=$dateInfo[0]->bill_status;
        $log_detail->extend_9=$tmpInfo.$tmpInfo1;
        $G_SHOP->DBCA->save($log_detail);
        //订单推送图文日志end


    }
    //获取access_token

    public function getAccess_token($appid,$appsecret){

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
        $result = file_get_contents($url);
        $result = json_decode($result,true);
        return $result;
    }



}